<template>
  <div class="markdown-editor" :data-theme-mode="isDarkMode ? 'dark' : 'light'" :style="themeVars">
    <!-- 预览区域现在在左侧 -->
    <div class="preview-container" :class="{ 'full-width': !showEditor }">
      <div class="markdown-body" v-html="renderedContent"></div>
    </div>
    
    <!-- 可调整大小的分隔条（包含切换按钮） -->
    <div 
      v-if="editable" 
      class="resizer"
      :class="{ 'resizer-collapsed': !showEditor }"
    >
      <div 
        v-if="showEditor"
        class="resizer-draggable"
        @mousedown="startResize"
      ></div>
      <div class="resizer-toggle" @click="toggleEditor">
        <span>{{ showEditor ? '›' : '‹' }}</span>
      </div>
    </div>
    
    <!-- 编辑器现在在右侧 -->
    <div v-if="editable && showEditor" class="editor-container" :style="{ width: editorWidth + 'px' }">
      <textarea
        v-model="localContent"
        class="editor"
        placeholder="请输入 Markdown 内容..."
      ></textarea>
    </div>
    
    <!-- 编辑弹窗 -->
    <EditModal
      v-model:visible="editModalVisible"
      :content="currentEditContent"
      :component-type="currentComponentType"
      @save="handleEditSave"
      @close="handleEditClose"
    />
  </div>
</template>

<script>
import 'katex/dist/katex.min.css'
import 'highlight.js/styles/github.css'
import 'github-markdown-css'
import { createMarkdownItInstance } from '../utils/markdownConfig'
import { EChartsRenderer } from '../plugins/markdownItEcharts'
import { DatasetRenderer } from '../plugins/markdownItDataset';
import { MermaidRenderer } from '../plugins/markdownItMermaid'
import { globalContainerRenderer } from '../plugins/markdownItContainer'
import EditModal from './EditModal.vue'
import mermaid from 'mermaid'
import { defaultTheme } from '../utils/defaultTheme'

export default {
  name: 'MarkdownEditor',
  components: {
    EditModal
  },
  props: {
    content: {
      type: String,
      default: ''
    },
    editable: {
      type: Boolean,
      default: false
    },
    defaultShowEditor: {
      type: Boolean,
      default: true
    },
    datasource: {
      type: Object,
      required: false,
      validator: (value) => {
        // 验证datasource对象是否包含必要的函数
        const requiredFunctions = ['getDataSource', 'getDataSourceList', 'clearDataSourceCache', 'testDataSourceConnection'];
        return requiredFunctions.every(func => typeof value[func] === 'function');
      }
    },
    dark: {
      type: [Boolean, String],
      default: 'auto',
      validator: (value) => value === 'auto' || typeof value === 'boolean'
    },
    theme: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:content', 'errors'],
  data() {
    return {
      localContent: this.content,
      showEditor: this.defaultShowEditor,
      md: null,
      chartRenderer: null,
      datasetRenderer: null,
      mermaidRenderer: null,
      renderTimeout: null,
      editModalVisible: false,
      currentEditContent: '',
      currentComponentType: '',
      currentComponentId: '',
      currentTokenStart: 0,
      currentTokenEnd: 0,
      // 拖动调整大小相关
      isResizing: false,
      editorWidth: 500, // 默认宽度500px
      minEditorWidth: 300, // 最小宽度
      maxEditorWidth: 800, // 最大宽度
      // 渲染错误收集
      renderErrors: [],
      // 挂载状态标记
      _isMounted: false,
      // 渲染状态标记，防止并发渲染
      _isRendering: false
    }
  },
  watch: {
    content: {
      handler(newVal) {
        if (this.localContent !== newVal) {
          this.localContent = newVal
        }
      },
      immediate: true
    },
    showEditor: {
      handler() {
        this.$nextTick(() => this.chartRenderer?.processEChartsElements())
      }
    }
  },
  created() {
    this.md = createMarkdownItInstance(this.editable)
    this.chartRenderer = new EChartsRenderer()
    this.datasetRenderer = new DatasetRenderer()
    this.mermaidRenderer = new MermaidRenderer()
    
    // 注入datasource到dataset插件
    this.datasetRenderer.setDataSourceFunctions(this.datasource)
    
    // 将dataset插件的实例级dataset对象传递给echarts插件
    this.chartRenderer.setDataset(this.datasetRenderer.getDataset())
    
    // 初始化Mermaid配置
    this.updateMermaidTheme()
  },
  computed: {
    renderedContent() {
      // 只负责渲染，不触发副作用
      // 防御性检查：确保 md 已初始化
      if (!this.md) return ''
      return this.md.render(this.localContent)
    },
    isDarkMode() {
      // 如果是 auto 模式，根据系统主题判断
      if (this.dark === 'auto') {
        if (typeof window !== 'undefined' && window.matchMedia) {
          return window.matchMedia('(prefers-color-scheme: dark)').matches
        }
        return false
      }
      return this.dark === true
    },
    themeVars() {
      // 合并用户自定义主题
      const mode = this.isDarkMode ? 'dark' : 'light'
      const baseTheme = defaultTheme[mode]
      const userTheme = this.theme[mode] || {}
      
      return { ...baseTheme, ...userTheme }
    }
  },
  watch: {
    // 监听 localContent 变化，触发异步渲染并 emit 事件
    localContent: {
      handler(newVal, oldVal) {
        // 触发 update:content 事件（用于 v-model）
        if (newVal !== oldVal && this._isMounted) {
          this.$emit('update:content', newVal)
        }
        
        if (this._isMounted && !this._isRendering) {
          // 使用防抖避免频繁渲染
          if (this.renderTimeout) {
            clearTimeout(this.renderTimeout)
          }
          this.renderTimeout = setTimeout(() => {
            this.$nextTick(() => {
              this.renderWithQueue()
            })
          }, 150)
        }
      }
    },
    // 监听主题变化，重新渲染所有内容
    isDarkMode: {
      handler() {
        if (this._isMounted) {
          // 更新 Mermaid 主题配置
          this.updateMermaidTheme()
          
          // 更新 ECharts 主题配置
          const theme = this.isDarkMode ? 'dark' : 'light'
          this.chartRenderer.setTheme(theme)
          
          // 清除所有已处理的标记，然后重新渲染
          this.$nextTick(() => {
            this.clearProcessedMarks()
            this.renderWithQueue()
          })
        }
      }
    }
  },
  mounted() {
    // 标记组件已挂载
    this._isMounted = true
    
    // 监听系统主题变化（仅在 auto 模式下）
    if (this.dark === 'auto' && typeof window !== 'undefined' && window.matchMedia) {
      this._themeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      this._handleThemeChange = () => {
        this.$forceUpdate() // 强制更新以重新计算 isDarkMode
      }
      this._themeMediaQuery.addEventListener('change', this._handleThemeChange)
    }
    
    // 使用事件委托处理可编辑元素的点击事件（完全避免全局变量）
    const previewContainer = this.$el.querySelector('.preview-container')
    if (previewContainer) {
      this._handleEditClick = (event) => {
        // 查找最近的可编辑元素
        const editableElement = event.target.closest('[data-editable="true"]')
        if (!editableElement) return
        
        event.stopPropagation()
        event.preventDefault()
        
        // 获取元素的位置和尺寸信息
        const rect = editableElement.getBoundingClientRect()
        
        // 定义编辑按钮区域（右上角20x20像素）
        const editButtonArea = {
          left: rect.right - 20,
          top: rect.top,
          right: rect.right,
          bottom: rect.top + 20
        }
        
        // 检查点击位置是否在编辑按钮区域内
        const isInEditButtonArea = 
          event.clientX >= editButtonArea.left && 
          event.clientX <= editButtonArea.right && 
          event.clientY >= editButtonArea.top && 
          event.clientY <= editButtonArea.bottom
        
        if (!isInEditButtonArea) return
        
        const componentId = editableElement.getAttribute('data-component-id')
        const componentType = editableElement.getAttribute('data-component-type')
        const positionInfo = editableElement.getAttribute('data-position')
        
        if (componentId && componentType && positionInfo) {
          // 从位置信息中提取 tokenStart 和 tokenEnd
          const [tokenStart, tokenEnd] = positionInfo.split(',').map(Number)
          
          // 从当前最新的 localContent 中提取内容（精准定位）
          const currentContent = this.localContent.substring(tokenStart, tokenEnd)
          
          this.currentComponentId = componentId
          this.currentComponentType = componentType
          this.currentEditContent = currentContent
          this.currentTokenStart = tokenStart
          this.currentTokenEnd = tokenEnd
          this.editModalVisible = true
        }
      }
      
      // 绑定事件监听器
      previewContainer.addEventListener('click', this._handleEditClick)
    }
    
    this.$nextTick(() => {
      // 初始化主题
      const theme = this.isDarkMode ? 'dark' : 'light'
      this.chartRenderer.setTheme(theme)
      
      // 开始渲染流程
      this.renderWithQueue()
      this.chartRenderer.observeDOM('.preview-container')
      this.datasetRenderer.observeDOM('.preview-container')
      this.mermaidRenderer.observeDOM('.preview-container')
    })
  },
  beforeUnmount() {
    // 标记组件已卸载
    this._isMounted = false
    
    // 清理定时器
    if (this.renderTimeout) {
      clearTimeout(this.renderTimeout)
      this.renderTimeout = null
    }
    
    // 清理主题监听器
    if (this._themeMediaQuery && this._handleThemeChange) {
      this._themeMediaQuery.removeEventListener('change', this._handleThemeChange)
      this._themeMediaQuery = null
      this._handleThemeChange = null
    }
    
    // 清理事件监听器
    const previewContainer = this.$el?.querySelector('.preview-container')
    if (previewContainer && this._handleEditClick) {
      previewContainer.removeEventListener('click', this._handleEditClick)
      this._handleEditClick = null
    }
    
    // 清理渲染器
    this.chartRenderer?.cleanup()
    this.datasetRenderer?.cleanup()
    this.mermaidRenderer?.cleanup()
  },
  methods: {
    /**
     * 清除所有已处理的标记，准备重新渲染
     */
    clearProcessedMarks() {
      const previewContainer = this.$el.querySelector('.preview-container')
      if (!previewContainer) return
      
      // 清除 Mermaid 已处理标记并恢复原始代码
      const mermaidElements = previewContainer.querySelectorAll('.mermaid[data-processed="true"]')
      mermaidElements.forEach(el => {
        el.removeAttribute('data-processed')
        // 恢复原始代码
        if (el.dataset.originalCode) {
          el.textContent = el.dataset.originalCode
        }
      })
      
      // 清除 ECharts 已处理标记
      const echartsElements = previewContainer.querySelectorAll('.echarts-container[data-processed="true"]')
      echartsElements.forEach(el => {
        el.removeAttribute('data-processed')
      })
      
      // 清除 Dataset 已处理标记
      const datasetElements = previewContainer.querySelectorAll('.dataset-container[data-processed="true"]')
      datasetElements.forEach(el => {
        el.removeAttribute('data-processed')
      })
    },
    
    updateMermaidTheme() {
      // 根据当前主题设置 Mermaid 主题
      const theme = this.isDarkMode ? 'dark' : 'default'
      mermaid.initialize({
        startOnLoad: true,
        theme: theme,
        securityLevel: 'loose',
        fontFamily: 'inherit',
        flowchart: {
          htmlLabels: true,
          useMaxWidth: true
        }
      })
    },
    handleResizerMouseDown(event) {
      // emit 事件，渲染由 watch: renderedContent 自动触发
      this.$emit('update:content', this.localContent)
    },
    async renderWithQueue() {
      // 防止并发渲染
      if (this._isRendering) {
        return
      }
      
      this._isRendering = true
      
      try {
        // 清空渲染器错误
        this.chartRenderer.clearErrors()
        this.datasetRenderer.clearErrors()
        this.mermaidRenderer.clearErrors()
        globalContainerRenderer.clearErrors()
        
        // 先渲染数据集（等待完成）
        await this.datasetRenderer.renderDatasets()
        
        // 等待 DOM 更新完成后再渲染图表
        await this.$nextTick()
        
        // 数据集渲染完成后，渲染图表
        this.chartRenderer.processEChartsElements()
        this.mermaidRenderer.renderMermaidCharts()
        
        // 延迟收集错误，确保所有异步渲染完成（优化延迟时间）
        setTimeout(() => {
          this.collectRenderErrors()
        }, 300)
      } catch (error) {
        console.warn('渲染过程中发生错误:', error)
        setTimeout(() => {
          this.collectRenderErrors()
        }, 300)
      } finally {
        this._isRendering = false
      }
    },
    
    // 暴露给外部的方法：获取所有错误
    getErrors() {
      return [...this.renderErrors]
    },
    
    collectRenderErrors() {
      const errors = []
      const lines = this.localContent.split('\n')
      
      // 从各个渲染器收集错误
      const allErrors = [
        ...this.chartRenderer.getErrors(),
        ...this.datasetRenderer.getErrors(),
        ...this.mermaidRenderer.getErrors(),
        ...globalContainerRenderer.getErrors()
      ]
      
      allErrors.forEach(err => {
        const errorInfo = this.findErrorLocation(err.message, lines, err.type, err.code)
        if (errorInfo) {
          errors.push(errorInfo)
        }
      })
      
      // 更新错误列表并触发事件
      this.renderErrors = errors
      this.$emit('errors', errors)
    },
    
    findErrorLocation(errorText, lines, hintType = null, errorCode = null) {
      // 尝试从错误文本中提取有用信息
      let lineNumber = -1
      let errorType = hintType || 'Unknown'
      let description = errorText
      
      // 识别错误类型
      if (!hintType) {
        if (errorText.includes('ECharts')) {
          errorType = 'ECharts'
        } else if (errorText.includes('数据集') || errorText.includes('dataset')) {
          errorType = 'Dataset'
        } else if (errorText.includes('Mermaid')) {
          errorType = 'Mermaid'
        }
      }
      
      // 在源码中查找相关代码块
      // 优先使用 errorCode 精确匹配，否则使用最后一个匹配的代码块
      let foundLines = []
      let exactMatch = -1
      
      for (let i = 0; i < lines.length; i++) {
        const line = lines[i]
        
        // 查找代码块标记
        if (errorType === 'ECharts' && line.includes('```echarts')) {
          foundLines.push(i + 1)
        } else if (errorType === 'Dataset' && line.includes('```dataset')) {
          foundLines.push(i + 1)
          // 如果有 errorCode，尝试精确匹配
          if (errorCode && errorCode.includes(line.trim())) {
            exactMatch = i + 1
          }
        } else if (errorType === 'Mermaid' && line.includes('```mermaid')) {
          foundLines.push(i + 1)
        } else if (errorType === 'Container' && line.includes('::: cell')) {
          foundLines.push(i + 1)
        }
      }
      
      // 只使用精确匹配
      if (exactMatch > 0) {
        lineNumber = exactMatch
      }
      
      // 如果找到了位置，提取代码片段
      if (lineNumber > 0) {
        const startLine = Math.max(0, lineNumber - 1)
        // 找到代码块的结束位置
        let endLine = startLine + 1
        
        if (errorType === 'Container') {
          // Container 使用 ::: 作为结束标记
          for (let i = startLine + 1; i < lines.length; i++) {
            if (lines[i].trim() === ':::') {
              endLine = i + 1
              break
            }
          }
        } else {
          // 其他类型使用 ``` 作为结束标记
          for (let i = startLine + 1; i < lines.length; i++) {
            if (lines[i].trim() === '```') {
              endLine = i + 1
              break
            }
          }
        }
        
        endLine = Math.min(lines.length, endLine)
        const codeSnippet = lines.slice(startLine, endLine).join('\n')
        
        // 清理错误消息
        let cleanMessage = description
          .replace(/^(ECharts|数据集|Mermaid|Container)(渲染|配置处理)?错误:\s*/i, '')
          .replace(/\s*at\s+.*$/gm, '') // 移除堆栈跟踪
          .split('\n')[0] // 只取第一行
          .trim()
        
        return {
          line: lineNumber,
          type: errorType,
          message: cleanMessage,
          code: codeSnippet,
          severity: 'error'
        }
      }
      
      return null
    },

    handleEditSave(newContent) {
      // 更新对应的markdown内容
      if (this.currentComponentId && this.currentComponentType) {
        const tokenStart = this.currentTokenStart
        const tokenEnd = this.currentTokenEnd
        
        // 使用精确的位置信息进行替换
        let updatedContent = this.localContent
        
        if (tokenStart !== undefined && tokenEnd !== undefined) {
          // 使用精确的位置替换内容
          const beforeContent = this.localContent.substring(0, tokenStart)
          const afterContent = this.localContent.substring(tokenEnd)
          
          // 直接替换原始内容
          updatedContent = beforeContent + newContent + afterContent
          
          // 计算长度变化
          const oldLength = tokenEnd - tokenStart
          const newLength = newContent.length
          const lengthDiff = newLength - oldLength
          
          // 如果长度有变化，需要更新后续所有可编辑元素的位置
          if (lengthDiff !== 0) {
            this.$nextTick(() => {
              this._updateSubsequentPositions(tokenEnd, lengthDiff)
            })
          }
        } else {
          console.error('未找到精确位置信息，无法进行内容替换')
          return
        }
        
        // 更新内容（watch: localContent 会自动触发渲染）
        this.localContent = updatedContent
        this.$emit('update:content', updatedContent)
        
        // 关闭弹窗
        this.editModalVisible = false
      }
    },
    
    /**
     * 更新后续元素的位置信息
     */
    _updateSubsequentPositions(changedEndPos, lengthDiff) {
      const editableElements = document.querySelectorAll('[data-editable="true"][data-position]')
      
      editableElements.forEach(element => {
        const positionInfo = element.getAttribute('data-position')
        if (!positionInfo) return
        
        const [start, end] = positionInfo.split(',').map(Number)
        
        // 只更新在修改位置之后的元素
        if (start >= changedEndPos) {
          const newStart = start + lengthDiff
          const newEnd = end + lengthDiff
          element.setAttribute('data-position', `${newStart},${newEnd}`)
        }
      })
    },
    handleEditClose() {
      this.editModalVisible = false
      this.currentComponentId = ''
      this.currentComponentType = ''
      this.currentEditContent = ''
      this.currentTokenStart = 0
      this.currentTokenEnd = 0
    },
    
    toggleEditor() {
      this.showEditor = !this.showEditor
    },
    
    // 开始调整大小
    startResize(event) {
      this.isResizing = true
      document.addEventListener('mousemove', this.handleResize)
      document.addEventListener('mouseup', this.stopResize)
      event.preventDefault()
    },
    
    // 处理调整大小
    handleResize(event) {
      if (!this.isResizing) return
      
      const container = this.$el
      const containerRect = container.getBoundingClientRect()
      
      // 计算新的编辑器宽度（从右边界到鼠标位置的距离）
      const newWidth = containerRect.right - event.clientX
      
      // 限制宽度在最小值和最大值之间
      if (newWidth >= this.minEditorWidth && newWidth <= this.maxEditorWidth) {
        this.editorWidth = newWidth
      }
    },
    
    // 停止调整大小
    stopResize() {
      this.isResizing = false
      document.removeEventListener('mousemove', this.handleResize)
      document.removeEventListener('mouseup', this.stopResize)
      
      // 调整大小后重新渲染图表
      this.$nextTick(() => {
        this.chartRenderer?.processEChartsElements()
      })
    }
  }
}</script>

<style scoped>
.markdown-editor {
  display: flex;
  height: 100%;
  overflow: hidden;
}

/* 确保 CSS 变量可以被子元素继承 */
.markdown-editor :deep(*) {
  /* CSS 变量会自动继承 */
}

/* 预览区域在左侧 */
.preview-container {
  flex: 1;
  height: 100%;
  position: relative;
  order: 1; /* 左侧第一项 */
  display: flex;
  justify-content: center; /* 内容居中 */
  background-color: var(--md-bg-primary); /* 使用主题变量 */
}

/* 可调整大小的分隔条 */
.resizer {
  width: auto;
  min-width: 2px;
  height: 100%;
  background-color: var(--md-editor-bg);
  order: 2;
  flex-shrink: 0;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 收起状态的分隔条 */
.resizer-collapsed {
  /* 继承 .resizer 的背景色 */
}

/* 可拖动区域 */
.resizer-draggable {
  position: absolute;
  left: 0;
  top: 0;
  width: 2px;
  height: 100%;
  background-color: var(--md-resizer-bg);
  cursor: col-resize;
  transition: background-color 0.2s ease;
}

.resizer-draggable:hover {
  background-color: var(--md-resizer-hover-bg);
}

.resizer-draggable::before {
  content: '';
  position: absolute;
  left: -2px;
  right: -2px;
  top: 0;
  bottom: 0;
}

/* 切换按钮 */
.resizer-toggle {
  width: 8px;
  height: 60px;
  background-color: var(--md-resizer-toggle-bg);
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 10;
  transition: all 0.2s ease;
  font-size: 20px;
  color: var(--md-resizer-toggle-text);
  user-select: none;
  position: relative;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 扩大点击热区 */
.resizer-toggle::before {
  content: '';
  position: absolute;
  left: -8px;
  right: -8px;
  top: -10px;
  bottom: -10px;
}

.resizer-toggle:hover {
  background-color: var(--md-resizer-toggle-hover-bg);
  color: white;
  transform: scale(1.1);
}

/* 编辑器在右侧，可调整宽度 */
.editor-container {
  height: 100%;
  position: relative;
  order: 3; /* 右侧第三项（分隔条后） */
  flex-shrink: 0; /* 防止宽度被压缩 */
}

.preview-container {
  overflow-y: auto;
  overflow-x: hidden;
}

/* 当编辑器隐藏时，预览区域占满宽度 */
.preview-container.full-width {
  flex: 1;
  max-width: 100%;
  order: 1;
}


.editor {
  width: 100%;
  height: 100%;
  border: none;
  outline: none;
  resize: none;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
  font-size: 12px;
  line-height: 1.6;
  background-color: var(--md-editor-bg);
  padding: 12px; /* 为编辑器文本区域添加内边距 */
  border-radius: 4px; /* 添加圆角边框 */
  color: var(--md-text-primary);
}

/* Markdown 预览区域样式 */
:deep(.markdown-body) {
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif;
  font-size: 13px;
  line-height: 1.5;
  word-wrap: break-word;
  padding: 16px;
  height: auto;
  min-height: 100%;
  box-sizing: border-box;
  background-color: var(--md-bg-primary) !important;
  width: 100%; /* 宽度100%适应容器 */
  color: var(--md-text-primary) !important;
}

/* 强制覆盖所有文本元素的颜色 */
:deep(.markdown-body *) {
  color: var(--md-text-primary);
}

/* 标题颜色 */
:deep(.markdown-body h1),
:deep(.markdown-body h2),
:deep(.markdown-body h3),
:deep(.markdown-body h4),
:deep(.markdown-body h5),
:deep(.markdown-body h6) {
  color: var(--md-text-primary) !important;
}

/* 段落和列表 */
:deep(.markdown-body p),
:deep(.markdown-body li),
:deep(.markdown-body ul),
:deep(.markdown-body ol) {
  color: var(--md-text-primary) !important;
}

/* 链接颜色 */
:deep(.markdown-body a) {
  color: var(--md-text-link) !important;
}

/* 引用块 */
:deep(.markdown-body blockquote) {
  color: var(--md-text-secondary) !important;
  border-left-color: var(--md-border-primary) !important;
}

/* 代码块 */
:deep(.markdown-body code) {
  background-color: var(--md-bg-code-inline) !important;
  color: var(--md-text-code) !important;
}

:deep(.markdown-body pre) {
  background-color: var(--md-bg-code) !important;
}

:deep(.markdown-body pre code) {
  color: var(--md-text-code) !important;
  background-color: transparent !important;
}

/* 水平线 */
:deep(.markdown-body hr) {
  background-color: var(--md-border-primary) !important;
  border-color: var(--md-border-primary) !important;
}

/* 强制覆盖 github-markdown-css 的表格样式 */
.markdown-editor :deep(.markdown-body table th),
.markdown-editor :deep(.markdown-body table td) {
  padding: 4px 8px !important;
  border: 1px solid var(--md-border-primary) !important;
  font-size: 12px !important;
  line-height: 1.4 !important;
  vertical-align: middle !important;
  min-height: 32px !important;
  box-sizing: border-box !important;
  color: var(--md-text-primary) !important;
}

.markdown-editor :deep(.markdown-body table th) {
  font-weight: 600 !important;
  background-color: var(--md-bg-secondary) !important;
  color: var(--md-text-primary) !important;
}

.markdown-editor :deep(.markdown-body table tr) {
  border-top: 1px solid var(--md-border-primary) !important;
  background-color: transparent !important;
}

.markdown-editor :deep(.markdown-body table) {
  color: var(--md-text-primary) !important;
}

/* 修改标题字体大小 */
:deep(.markdown-body h1) {
  font-size: 20px;
  margin-top: 0.5em;
  margin-bottom: 1em;
  border-bottom: none !important;
}

:deep(.markdown-body h2) {
  font-size: 18px;
  margin-top: 0.5em;
  margin-bottom: 1em;
  border-bottom: none !important;
}

:deep(.markdown-body h3) {
  font-size: 13px;
  margin-top: 0.5em;
  margin-bottom: 1em;
  border-bottom: none !important;
}

:deep(.markdown-body h4) {
  font-size: 14px;
  margin-top: 0.5em;
  margin-bottom: 1em;
  border-bottom: none !important;
}

:deep(.dataset-header h4) {
  margin-top: 0 !important;
  margin-bottom: 0 !important;
}

:deep(.markdown-body h5) {
  font-size: 13px;
  margin-top: 0.5em;
  margin-bottom: 1em;
  border-bottom: none !important;
}

:deep(.markdown-body h6) {
  font-size: 12px;
  margin-top: 0.5em;
  margin-bottom: 1em;
  border-bottom: none !important;
}

/* 调整代码字体大小 */
:deep(.markdown-body code) {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
  font-size: 12px;
  border-radius: 6px;
  padding: 0.2em 0.4em;
}

:deep(.markdown-body pre) {
  border-radius: 6px;
  padding: 16px;
}

:deep(.markdown-body pre code) {
  font-size: 12px;
  background-color: transparent;
  padding: 0;
}

:deep(.markdown-body table) {
  display: block;
  width: 100%;
  overflow: auto;
  border-spacing: 0;
  border-collapse: collapse;
}

/* 更新任务列表样式 */
:deep(.task-list-item) {
  list-style-type: none;
}

:deep(.task-list-item input[type="checkbox"]) {
  margin: 0 0.2em 0.25em -1.6em;
  vertical-align: middle;
}

:deep(.task-list-item + .task-list-item) {
  margin-top: 3px;
}

:deep(.task-list-item.enabled label) {
  cursor: pointer;
}

:deep(ul.contains-task-list) {
  padding-left: 30px;
}

/* 隐藏空段落 */
:deep(p:empty) {
  display: none;
}

/* 自定义滚动条样式 */
.editor,
.preview-container {
  scrollbar-width: thin; /* Firefox */
  scrollbar-color: var(--md-scrollbar-thumb) var(--md-scrollbar-track); /* Firefox */
}

/* Webkit (Chrome, Safari, Edge) 滚动条样式 */
.editor::-webkit-scrollbar,
.preview-container::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.editor::-webkit-scrollbar-track,
.preview-container::-webkit-scrollbar-track {
  background: var(--md-scrollbar-track);
}

.editor::-webkit-scrollbar-thumb,
.preview-container::-webkit-scrollbar-thumb {
  background: var(--md-scrollbar-thumb);
  border-radius: 3px;
}

.editor::-webkit-scrollbar-thumb:hover,
.preview-container::-webkit-scrollbar-thumb:hover {
  background: var(--md-scrollbar-thumb-hover);
}
</style>